package com.tbit.main.config.nacos;

import com.tbit.main.constant.*;
import com.tbit.main.pojo.HostList;
import com.tbit.main.pojo.LinkConfigList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.cloud.endpoint.event.RefreshEventListener;
import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * nacos配置刷新事件监听
 *
 * @Author:BUGTian
 * @DATE: 2022/10/13
 */
@Component
@Slf4j
public class ConfigRefreshEventListener extends RefreshEventListener {
    @Autowired
    private AliOssConstant aliOssConstant;
    @Autowired
    private LinkConfigList linkConfigList;
    @Autowired
    private HostList hostList;
    @Autowired
    private SysConstant sysConstant;
    @Autowired
    private AppPushConstant appPushConstant;
    @Autowired
    private SystemData systemData;
    @Autowired
    private UqbikeManagerConfig uqbikeManagerConfig;

    private ContextRefresher refresh;
    private AtomicBoolean ready = new AtomicBoolean(false);

    public ConfigRefreshEventListener(ContextRefresher refresh) {
        super(refresh);
        this.refresh = refresh;
    }

    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationReadyEvent.class.isAssignableFrom(eventType) || RefreshEvent.class.isAssignableFrom(eventType);
    }

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationReadyEvent) {
            this.handle((ApplicationReadyEvent) event);
        } else if (event instanceof RefreshEvent) {
            this.handle((RefreshEvent) event);
        }

    }

    @Override
    public void handle(ApplicationReadyEvent event) {
        this.ready.compareAndSet(false, true);
    }

    @Override
    public void handle(RefreshEvent event) {
        if (this.ready.get()) {
            Set<String> keys = this.refresh.refresh();
            log.info("配置刷新key={}", keys);
            aliOssConstant.refresh();
            linkConfigList.refresh();
            hostList.refresh();
            sysConstant.refresh();
            appPushConstant.refresh();
            systemData.refresh();
            uqbikeManagerConfig.refresh();
        }

    }
}
